package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @package: com.cskaoyan.typehandler
 * @Description: Integer类型参数自动转换成Boolean类型的转换器
 * @author: 北青
 * @date: 2022/1/7 17:04
 */
@MappedTypes(Boolean.class)
@MappedJdbcTypes(JdbcType.TINYINT)
public class BooleanTypeHandler implements TypeHandler<Boolean> {


    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Boolean aBoolean, JdbcType jdbcType) throws SQLException {
        //Boolean → Integer
        int status = aBoolean ? 1 : 0;
        preparedStatement.setInt(i, status);
    }

    @Override
    public Boolean getResult(ResultSet resultSet, String s) throws SQLException {
        int result = Integer.parseInt(resultSet.getString(s));
        return result == 1;
    }

    @Override
    public Boolean getResult(ResultSet resultSet, int i) throws SQLException {
        return Integer.parseInt(resultSet.getString(i)) == 1;
    }

    @Override
    public Boolean getResult(CallableStatement callableStatement, int i) throws SQLException {
        return callableStatement.getBoolean(i);
    }
}
